# $Id$

"""
sk/admin.py
-----------

Main admin interface for sk
"""

__author__ = 'Pat Smith <pat@waldosmith.com>'
__docformat__ = 'restructuredtext en'
__version__ = '$Revision$'[11:-2]

from datetime import datetime, timedelta
from django import forms
from django.contrib.auth.decorators import login_required
from django.template import Context, loader
from django.http import HttpResponse
from monulu.raid.models import Raid, Instance 

class NewRaidForm(forms.Form):
    instance = forms.ChoiceField(label=u'Instance')
    size = forms.IntegerField(label=u'Size', initial=12)
    start = forms.DateTimeField(label=u'Start time')
    end = forms.CharField(label=u'Ends', required=False, initial='-')
    def __init__(self, request=None, **kwargs):
        self.request = request
        if request and self.request.method == 'POST':
            kwargs['data'] = self.request.POST
        super(NewRaidForm, self).__init__(**kwargs)
        self.fields['instance'].choices = [(i.id,i) for i in Instance.objects.all()]
        self.fields['start'].initial=datetime.now()
    
@login_required
def admin(request):
    if request.method == 'POST':
        newRaidForm = NewRaidForm(request)
        if newRaidForm.is_valid():
            raid = Raid()
            raid.characters_required = newRaidForm.cleaned_data['size']
            raid.instance = Instance.objects.get(pk=newRaidForm.cleaned_data['instance'])
            raid.start_time = newRaidForm.cleaned_data['start']
            raid.end = newRaidForm.cleaned_data['end']
            raid.save()
    else:
        newRaidForm = NewRaidForm()
        
    yesterday = datetime.today() - timedelta(5) # list raids up to x days old 
    raids = Raid.objects.filter(start_time__gte=yesterday).order_by('-start_time')
    t = loader.get_template('sk/admin.html')
    c = Context({'raids':raids, 'newRaidForm':newRaidForm})
    return HttpResponse(t.render(c))

